package cc.cix.hq.auth.service;

import cc.cix.hq.common.core.client.IUserClient;
import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;

import java.util.HashMap;
import java.util.Map;

/**
 * @author cix
 */
public class JWTokenEnhancer implements TokenEnhancer {

    @Reference
    private IUserClient userClient;

    @SneakyThrows
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {
        User principal = (User) oAuth2Authentication.getUserAuthentication().getPrincipal();
        String mobile = principal.getUsername();
        cc.cix.hq.common.core.entity.org.User user = userClient.getUserByMobile(mobile);
        String userJson = JSONUtil.toJsonStr(user);

        Map<String, Object> info = new HashMap<>(1);
        info.put("user", userJson);
        ((DefaultOAuth2AccessToken) oAuth2AccessToken).setAdditionalInformation(info);
        return oAuth2AccessToken;
    }
}
